<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>drawPoint</title>
</head>
<body>
<canvas width="500" height="500" style="border: 1px solid #333333"></canvas>
</body>
<script>
    function createShader(gl,source,type) {
        const shader = gl.createShader(type)
        gl.shaderSource(shader,source)
        gl.compileShader(shader)
        const success = gl.getShaderParameter(shader,gl.COMPILE_STATUS)
        if(success){
            return shader
        }
        gl.deleteShader(shader)
    }

    function createProgram(gl,vShader,fShader) {
        const program = gl.createProgram()
        gl.attachShader(program,vShader)
        gl.attachShader(program,fShader)
        gl.linkProgram(program)
        const success = gl.getProgramParameter(program,gl.LINK_STATUS)
        if(success){
            return program
        }
        gl.deleteProgram(program)
    }

    function main() {
        const vSource = `
            attribute vec4 a_position;
            void main(){
                gl_Position = a_position;
                gl_PointSize = 10.0;
            }
        `

        const fSource = `
            void main(){
                gl_FragColor = vec4(1.0, 0.0, 0.0, 1.0);
            }
        `
        const canvas = document.querySelector('canvas')
        const gl = canvas.getContext('webgl')

        const vShader = createShader(gl,vSource,gl.VERTEX_SHADER)
        const fShader = createShader(gl,fSource,gl.FRAGMENT_SHADER)
        const program = createProgram(gl,vShader,fShader)
        const a_position = gl.getAttribLocation(program,'a_position')

        gl.useProgram(program)
        gl.clearColor(0.0,0.0,0.0,1.0)
        gl.clear(gl.COLOR_BUFFER_BIT)
        const points = []
        const rect = canvas.getBoundingClientRect()

         function _onmousemove(ev){
            const _clientX = ev.clientX
            const _clientY =ev.clientY

            const canvasX = _clientX - rect.left
            const canvasY = _clientY - rect.top

            const glX = (canvasX - rect.width / 2) / (rect.width / 2)
            const glY = (rect.height / 2 - canvasY) / (rect.height / 2)
            points.push(glX,glY)

            gl.clear(gl.COLOR_BUFFER_BIT)
            for(let i = 0; i < points.length; i+=2){
                gl.vertexAttrib3f(a_position, points[i], points[i+1], 0.0)
                gl.drawArrays(gl.POINTS, 0, 1)
            }
        }
        canvas.addEventListener('mousedown', function(){
            // debugger
            canvas.onmousemove = _onmousemove
            // canvas.addEventListener('onmousemove',_onmousemove)
        })
        canvas.addEventListener('mouseup',function () {
            canvas.onmousemove = null
            // canvas.removeEventListener('onmousemove',_onmousemove)
        })

    }
    main()
</script>
</html>